package cn.shyouchi.wuguanjia.android.ui.login;

import android.content.Context;
import android.support.annotation.NonNull;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.shyouchi.wuguanjia.android.api.youchi.YouChiApi;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.model.LoginMod;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Eenie on 2016/10/12 at 15:56
 * Email: 472279981@qq.com
 * Des:
 */

public class LoginPresenter implements LoginContract.Presenter {

    LoginContract.View mView;
    Context mContext;
    YouChiApi mApi;

    public LoginPresenter(Context context) {
        this.mContext = context;
        mApi = new YouChiApi();
    }

    @Override
    public void attachView(@NonNull LoginContract.View view) {
        this.mView = view;
    }

    @Override
    public void detachView() {

    }

    @Override
    public void login(String phone, String pwd) {
        mApi.login(phone, pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<LoginMod>(mContext) {
                    @Override
                    public void onNext(LoginMod mod) {
                        mView.jumpMain(mod);
                        Set<String> tags = new HashSet<>();
                        tags.add("project_id_" + mod.getData().getProject_id());
                        tags.add(mod.getData().getUnique());
                        JPushInterface.setAliasAndTags(mContext, "project_id_" + mod.getData().getProject_id(), tags, new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {
//                                LogUtil.json(set);
//                                LogUtil.e(String.format("%s %s ", i, s));
                            }
                        });
                        new UserStorage(mContext).save(mod.getData().getToken(), mod.getData());
                    }
                });
    }
}
